#!/usr/bin/env python3
"""
转码任务页面UI组件

包含源路径选择功能：
1. 选择文件和文件夹的二合一按钮
2. 显示路径的控件
3. 功能提示问号控件
"""

import os
from pathlib import Path
from PyQt6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QLabel, 
                             QLineEdit, QPushButton, QMessageBox, QFileDialog,
                             QToolButton, QSizePolicy, QDialog, QComboBox)
from PyQt6.QtCore import Qt, QSize
from PyQt6.QtGui import QIcon, QFont

# 导入视频尺寸组件
from video_size_widget import VideoSizeWidget
# 导入GPU加速组件
from gpu_acceleration_widget import GPUAccelerationWidget


class SourcePathWidget(QWidget):
    """源路径选择组件"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.selected_path = ""
        self.init_ui()
    
    def init_ui(self):
        """初始化UI"""
        # 主布局
        main_layout = QVBoxLayout()
        
        # 标题
        title_label = QLabel("📁 源路径选择")
        title_label.setFont(QFont("Microsoft YaHei", 12, QFont.Weight.Bold))
        title_label.setStyleSheet("color: #2c3e50; margin-bottom: 10px;")
        main_layout.addWidget(title_label)
        
        # 路径选择行
        path_layout = QHBoxLayout()
        
        # 路径显示控件
        self.path_display = QLineEdit()
        self.path_display.setPlaceholderText("请选择文件或文件夹路径...")
        self.path_display.setReadOnly(True)
        self.path_display.setStyleSheet("""
            QLineEdit {
                border: 1px solid #bdc3c7;
                border-radius: 4px;
                padding: 8px;
                background-color: #2c3e50;
                color: #ecf0f1;
                font-family: 'Microsoft YaHei', Arial, sans-serif;
                font-size: 11px;
                selection-background-color: #3498db;
            }
            QLineEdit:focus {
                border-color: #3498db;
                background-color: #34495e;
                color: #ffffff;
            }
        """)
        path_layout.addWidget(self.path_display)
        
        # 选择按钮（二合一：文件+文件夹）
        self.select_button = QToolButton()
        self.select_button.setText("📂 选择")
        self.select_button.setToolTip("选择文件或文件夹")
        self.select_button.setPopupMode(QToolButton.ToolButtonPopupMode.MenuButtonPopup)
        self.select_button.setStyleSheet("""
            QToolButton {
                background-color: #3498db;
                color: white;
                border: none;
                border-radius: 4px;
                padding: 8px 16px;
                font-family: 'Microsoft YaHei', Arial, sans-serif;
                font-size: 11px;
                font-weight: bold;
            }
            QToolButton:hover {
                background-color: #2980b9;
            }
            QToolButton:pressed {
                background-color: #21618c;
            }
        """)
        
        # 创建下拉菜单
        self._create_selection_menu()
        path_layout.addWidget(self.select_button)
        
        # 问号提示按钮
        self.help_button = QToolButton()
        self.help_button.setText("?")
        self.help_button.setToolTip("点击查看功能说明")
        self.help_button.setFixedSize(30, 30)
        self.help_button.setStyleSheet("""
            QToolButton {
                background-color: #95a5a6;
                color: white;
                border: none;
                border-radius: 15px;
                font-family: 'Microsoft YaHei', Arial, sans-serif;
                font-size: 14px;
                font-weight: bold;
            }
            QToolButton:hover {
                background-color: #7f8c8d;
            }
            QToolButton:pressed {
                background-color: #636e72;
            }
        """)
        self.help_button.clicked.connect(self.show_help_info)
        path_layout.addWidget(self.help_button)
        
        main_layout.addLayout(path_layout)
        
        # 路径信息显示
        self.info_label = QLabel("")
        self.info_label.setStyleSheet("""
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            font-size: 10px;
            color: #ffffff;
            margin-top: 5px;
            padding: 8px;
            background-color: #2c3e50;
            border-radius: 5px;
            border: 1px solid #3498db;
            font-weight: bold;
        """)
        main_layout.addWidget(self.info_label)
        
        self.setLayout(main_layout)
    
    def _create_selection_menu(self):
        """创建选择菜单"""
        from PyQt6.QtGui import QAction
        
        # 文件选择动作
        file_action = QAction("📄 选择文件", self)
        file_action.triggered.connect(self.select_file)
        
        # 文件夹选择动作
        folder_action = QAction("📁 选择文件夹", self)
        folder_action.triggered.connect(self.select_folder)
        
        # 添加到按钮菜单
        self.select_button.addAction(file_action)
        self.select_button.addAction(folder_action)
        
        # 设置默认点击行为为选择文件
        self.select_button.clicked.connect(self.select_file)
    
    def select_file(self):
        """选择文件"""
        file_path, _ = QFileDialog.getOpenFileName(
            self, 
            "选择视频文件", 
            "",
            "所有文件 (*.*)"
        )
        
        if file_path:
            self.selected_path = file_path
            self.path_display.setText(file_path)
            self._update_path_info(file_path)
    
    def select_folder(self):
        """选择文件夹"""
        folder_path = QFileDialog.getExistingDirectory(
            self, 
            "选择视频文件夹", 
            ""
        )
        
        if folder_path:
            self.selected_path = folder_path
            self.path_display.setText(folder_path)
            self._update_path_info(folder_path)
    
    def _update_path_info(self, path):
        """更新路径信息显示"""
        path_obj = Path(path)
        
        if path_obj.is_file():
            # 文件信息
            file_size = path_obj.stat().st_size
            size_mb = file_size / (1024 * 1024)
            info_text = f"📄 文件: {path_obj.name} | 大小: {size_mb:.2f} MB | 路径: {path_obj.parent}"
        else:
            # 文件夹信息
            try:
                video_files = list(path_obj.glob("*.mp4")) + list(path_obj.glob("*.avi")) + \
                            list(path_obj.glob("*.mkv")) + list(path_obj.glob("*.mov"))
                video_count = len(video_files)
                info_text = f"📁 文件夹: {path_obj.name} | 包含视频文件: {video_count} 个"
            except:
                info_text = f"📁 文件夹: {path_obj.name}"
        
        self.info_label.setText(info_text)
    
    def show_help_info(self):
        """显示帮助信息"""
        help_text = """
        <h3>📁 源路径选择功能说明</h3>
        
        <p><b>功能描述：</b></p>
        <ul>
        <li><b>选择文件：</b>选择单个视频文件进行转码</li>
        <li><b>选择文件夹：</b>选择包含多个视频文件的文件夹进行批量转码</li>
        </ul>
        
        <p><b>支持格式：</b></p>
        <ul>
        <li>支持所有ffmpeg兼容的视频格式</li>
        <li>包括但不限于：MP4、AVI、MKV、MOV、WMV、FLV、WebM、M4V、TS等</li>
        <li>支持.ts文件（如：Angelic Teens Sofy Soul 和 via Lasciva Melt a Young Mans Cock.ts）</li>
        </ul>
        
        <p><b>使用提示：</b></p>
        <ul>
        <li>点击 <b>📂 选择</b> 按钮或下拉箭头选择文件/文件夹</li>
        <li>路径信息将自动显示在下方</li>
        <li>支持拖放文件到路径显示区域</li>
        </ul>
        """
        
        QMessageBox.information(self, "源路径选择帮助", help_text)
    
    def get_selected_path(self):
        """获取选中的路径"""
        return self.selected_path
    
    def clear_selection(self):
        """清空选择"""
        self.selected_path = ""
        self.path_display.clear()
        self.info_label.clear()


class TranscodeTaskDialog(QDialog):
    """转码任务对话框"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("新建转码任务")
        self.setMinimumSize(600, 350)
        self.init_ui()
    
    def init_ui(self):
        """初始化UI"""
        # 主布局
        main_layout = QVBoxLayout()
        
        # 标题
        title_label = QLabel("🎬 新建转码任务")
        title_label.setFont(QFont("Microsoft YaHei", 16, QFont.Weight.Bold))
        title_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        title_label.setStyleSheet("""
            color: #2c3e50;
            margin: 20px;
            padding: 15px;
            background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                stop:0 #3498db, stop:1 #2c3e50);
            color: white;
            border-radius: 8px;
            font-size: 18px;
        """)
        main_layout.addWidget(title_label)
        
        # 源路径选择组件
        self.source_path_widget = SourcePathWidget(self)
        main_layout.addWidget(self.source_path_widget)
        
        # 转码设置行
        settings_layout = QHBoxLayout()
        
        # 转化格式选择
        format_label = QLabel("转化为：")
        format_label.setFont(QFont("Microsoft YaHei", 10, QFont.Weight.Bold))
        format_label.setStyleSheet("color: #2c3e50; min-width: 60px;")
        settings_layout.addWidget(format_label)
        
        self.format_combo = QComboBox()
        # ffmpeg支持的常见输出格式
        ffmpeg_formats = [
            "MP4", "AVI", "MKV", "MOV", "WMV", "FLV", "WebM", "M4V", "TS",
            "MPEG", "3GP", "OGG", "OGV", "M2TS", "MTS", "F4V", "RMVB", "ASF"
        ]
        self.format_combo.addItems(ffmpeg_formats)
        self.format_combo.setCurrentText("MP4")
        self.format_combo.setStyleSheet("""
            QComboBox {
                border: 1px solid #bdc3c7;
                border-radius: 4px;
                padding: 6px;
                background-color: #2c3e50;
                color: #ecf0f1;
                font-family: 'Microsoft YaHei', Arial, sans-serif;
                font-size: 11px;
                min-width: 120px;
            }
            QComboBox:focus {
                border-color: #3498db;
                background-color: #34495e;
            }
            QComboBox QAbstractItemView {
                background-color: #2c3e50;
                color: #ecf0f1;
                selection-background-color: #3498db;
            }
        """)
        settings_layout.addWidget(self.format_combo)
        
        # 添加间距
        settings_layout.addSpacing(40)
        
        # 目标路径选择
        target_label = QLabel("存储位置：")
        target_label.setFont(QFont("Microsoft YaHei", 10, QFont.Weight.Bold))
        target_label.setStyleSheet("color: #2c3e50; min-width: 80px;")
        settings_layout.addWidget(target_label)
        
        self.target_path_display = QLineEdit()
        self.target_path_display.setPlaceholderText("请选择转码文件存储位置...")
        self.target_path_display.setReadOnly(True)
        self.target_path_display.setStyleSheet("""
            QLineEdit {
                border: 1px solid #bdc3c7;
                border-radius: 4px;
                padding: 8px;
                background-color: #2c3e50;
                color: #ecf0f1;
                font-family: 'Microsoft YaHei', Arial, sans-serif;
                font-size: 11px;
                selection-background-color: #3498db;
                min-width: 200px;
            }
            QLineEdit:focus {
                border-color: #3498db;
                background-color: #34495e;
                color: #ffffff;
            }
        """)
        settings_layout.addWidget(self.target_path_display)
        
        self.target_select_button = QPushButton("选择")
        self.target_select_button.setStyleSheet("""
            QPushButton {
                background-color: #3498db;
                color: white;
                border: none;
                border-radius: 4px;
                padding: 8px 16px;
                font-family: 'Microsoft YaHei', Arial, sans-serif;
                font-size: 11px;
                font-weight: bold;
                min-width: 60px;
            }
            QPushButton:hover {
                background-color: #2980b9;
            }
            QPushButton:pressed {
                background-color: #21618c;
            }
        """)
        self.target_select_button.clicked.connect(self.select_target_folder)
        settings_layout.addWidget(self.target_select_button)
        
        settings_layout.addStretch()
        main_layout.addLayout(settings_layout)
        
        # 视频尺寸调整组件
        self.video_size_widget = VideoSizeWidget(self)
        main_layout.addWidget(self.video_size_widget)
        
        # GPU加速组件
        self.gpu_acceleration_widget = GPUAccelerationWidget(self)
        main_layout.addWidget(self.gpu_acceleration_widget)
        
        # 添加分隔线
        separator = QLabel("─" * 80)
        separator.setAlignment(Qt.AlignmentFlag.AlignCenter)
        separator.setStyleSheet("color: #bdc3c7; margin: 15px 0;")
        main_layout.addWidget(separator)
        
        # 按钮区域
        button_layout = QHBoxLayout()
        
        # 确定按钮
        ok_button = QPushButton("✅ 确定")
        ok_button.setStyleSheet("""
            QPushButton {
                background-color: #27ae60;
                color: white;
                border: none;
                border-radius: 6px;
                padding: 10px 20px;
                font-family: 'Microsoft YaHei', Arial, sans-serif;
                font-size: 12px;
                font-weight: bold;
                min-width: 80px;
            }
            QPushButton:hover {
                background-color: #229954;
            }
            QPushButton:pressed {
                background-color: #1e8449;
            }
        """)
        ok_button.clicked.connect(self.accept_task)
        
        # 取消按钮
        cancel_button = QPushButton("❌ 取消")
        cancel_button.setStyleSheet("""
            QPushButton {
                background-color: #e74c3c;
                color: white;
                border: none;
                border-radius: 6px;
                padding: 10px 20px;
                font-family: 'Microsoft YaHei', Arial, sans-serif;
                font-size: 12px;
                font-weight: bold;
                min-width: 80px;
            }
            QPushButton:hover {
                background-color: #c0392b;
            }
            QPushButton:pressed {
                background-color: #a93226;
            }
        """)
        cancel_button.clicked.connect(self.reject_task)
        
        # 清空按钮
        clear_button = QPushButton("🗑️ 清空")
        clear_button.setStyleSheet("""
            QPushButton {
                background-color: #95a5a6;
                color: white;
                border: none;
                border-radius: 6px;
                padding: 10px 20px;
                font-family: 'Microsoft YaHei', Arial, sans-serif;
                font-size: 12px;
                font-weight: bold;
                min-width: 80px;
            }
            QPushButton:hover {
                background-color: #7f8c8d;
            }
            QPushButton:pressed {
                background-color: #636e72;
            }
        """)
        clear_button.clicked.connect(self.clear_task)
        
        button_layout.addStretch()
        button_layout.addWidget(clear_button)
        button_layout.addWidget(cancel_button)
        button_layout.addWidget(ok_button)
        
        main_layout.addLayout(button_layout)
        
        self.setLayout(main_layout)
    
    def accept_task(self):
        """接受任务"""
        selected_path = self.source_path_widget.get_selected_path()
        
        if not selected_path:
            QMessageBox.warning(self, "警告", "请先选择源文件或文件夹！")
            return
        
        # 验证路径是否存在
        if not os.path.exists(selected_path):
            QMessageBox.critical(self, "错误", "选择的路径不存在！")
            return
        
        # 验证GPU加速设置
        if not self.gpu_acceleration_widget.has_selected_hardware():
            QMessageBox.warning(self, "警告", "请至少选择一个硬件进行转码！")
            return
        
        # 获取任务设置
        gpu_settings = self.gpu_acceleration_widget.get_acceleration_settings()
        
        # 显示任务信息
        path_obj = Path(selected_path)
        if path_obj.is_file():
            message = f"✅ 已创建转码任务\n\n文件: {path_obj.name}\n路径: {path_obj.parent}"
        else:
            message = f"✅ 已创建批量转码任务\n\n文件夹: {path_obj.name}\n路径: {selected_path}"
        
        # 添加GPU加速信息
        if gpu_settings["gpu_acceleration_enabled"]:
            hardware_info = []
            if gpu_settings["cpu"]["enabled"]:
                hardware_info.append(f"CPU({gpu_settings['cpu']['task_count']}任务)")
            if gpu_settings["integrated_gpu"]["enabled"]:
                hardware_info.append(f"集显({gpu_settings['integrated_gpu']['task_count']}任务)")
            if gpu_settings["dedicated_gpu"]["enabled"]:
                hardware_info.append(f"独显({gpu_settings['dedicated_gpu']['task_count']}任务)")
            
            message += f"\n\n⚡ GPU加速: 启用\n硬件: {' + '.join(hardware_info)}\n总并行任务: {gpu_settings['total_parallel_tasks']}"
        else:
            message += "\n\n⚡ GPU加速: 禁用（使用CPU转码）"
        
        QMessageBox.information(self, "任务创建成功", message)
        
        # 这里可以添加实际的任务创建逻辑
        print(f"转码任务创建成功 - 源路径: {selected_path}")
        print(f"GPU加速设置: {gpu_settings}")
    
    def reject_task(self):
        """取消任务"""
        self.close()
    
    def select_target_folder(self):
        """选择目标文件夹"""
        folder_path = QFileDialog.getExistingDirectory(
            self, 
            "选择转码文件存储位置", 
            ""
        )
        
        if folder_path:
            self.target_path_display.setText(folder_path)
    
    def clear_task(self):
        """清空任务设置"""
        self.source_path_widget.clear_selection()
        self.target_path_display.clear()
        self.format_combo.setCurrentText("MP4")
        
        # 重置GPU加速设置
        self.gpu_acceleration_widget.reset_settings()
        
        QMessageBox.information(self, "清空成功", "所有设置已清空，可以重新配置。")


if __name__ == "__main__":
    # 测试代码
    import sys
    from PyQt6.QtWidgets import QApplication
    
    app = QApplication(sys.argv)
    
    # 测试源路径组件
    source_widget = SourcePathWidget()
    source_widget.show()
    
    # 测试完整对话框
    # dialog = TranscodeTaskDialog()
    # dialog.show()
    
    sys.exit(app.exec())